package main

import (
	"flag"
	"fmt"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/text/gstr"
	"github.com/tal-tech/go-zero/core/conf"
	"github.com/tal-tech/go-zero/rest"
	"net/http"
	"shape-erver/internal/config"
	"shape-erver/internal/handler"
	"shape-erver/internal/svc"
	"shape-erver/task_process"
	"shape-erver/utils"
)

var (
	configFile = flag.String("f", "etc/shapeServer-api.yaml", "the config file")
	gfcfgFile  = flag.String("gffile", "config.yaml", "the gf config file")
	gfcfgPath  = flag.String("gfpath", "./etc", "the gf config file")
)

const (
	allowOrigin              = "Access-Control-Allow-Origin"
	allOrigins               = "*"
	allowCredentialsTrue     = "true"
	allowMethods             = "Access-Control-Allow-Methods"
	allowHeaders             = "Access-Control-Allow-Headers"
	headers                  = "Content-Type, Content-Length,Origin,Authorization,X-Requested-With,X-Forwarded-For,X-Forwarded-Host,X-Forwarded-Port,X-Forwarded-Proto,sst"
	methods                  = "GET, HEAD, POST, PATCH, PUT, DELETE"
	allowCredentials         = "Access-Control-Allow-Credentials"
	accessControlMaxAge      = "Access-Control-Max-Age"
	accessControlMaxAgeValue = "1728000"

	accessControlExposeHeaders = "Access-Control-Expose-Headers"
	ExposeHeaders              = "nt,sst"
)

// CorsHandler handles cross domain OPTIONS requests.
// At most one origin can be specified, other origins are ignored if given.
func CorsHandler(origins ...string) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if len(origins) > 0 {
			w.Header().Set(allowOrigin, origins[0])
		} else {
			org := r.Header.Get("Origin")
			// fmt.Println("main org " + org)
			w.Header().Set(allowOrigin, org)
		}
		w.Header().Set(allowMethods, methods)
		w.Header().Set(allowHeaders, headers)
		w.Header().Set(allowCredentials, allowCredentialsTrue)
		w.Header().Set(accessControlMaxAge, accessControlMaxAgeValue)
		w.Header().Set(accessControlExposeHeaders, ExposeHeaders)
		method := gstr.ToLower(r.Method)
		if method == "options" {
			w.WriteHeader(http.StatusNoContent)
			return
		}
		w.WriteHeader(http.StatusNoContent)
	})
}

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c)
	g.Cfg().SetPath(*gfcfgPath)
	g.Cfg().SetFileName(*gfcfgFile)

	ctx := svc.NewServiceContext(c)
	utils.LoadA(ctx)
	server := rest.MustNewServer(c.RestConf, rest.WithNotAllowedHandler(CorsHandler()))
	//server.Use(ctx.Cros)
	defer server.Stop()

	handler.RegisterHandlers(server, ctx)

	task_process.StartServer()

	fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
	server.Start()
}
